package com.qinghuan.threads.chapterTwo;

/**
 * @Author: dubao
 * @Date: 2022/5/21 10:07
 * @Description:
 */

/**
 * Java指令重排序问题
 */
public class Test2_10_1 {

    public static class ReadThread extends Thread {
        @Override
        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                if (ready) {
                    System.out.println(num + num);
                }
                System.out.println("read thread...");
            }
        }
    }

    public static class WriteThread extends Thread {
        @Override
        public void run() {
            //下面的两行代码在多线程运行的情况下顺序不一定，所以会导致输出结果不一样
            num = 2;
            ready = true;
            System.out.println("writeThread set over...");
        }
    }

    private static int num = 0;
    private static boolean ready = false;

    public static void main(String[] args) throws InterruptedException {
        ReadThread readThread = new ReadThread();
        readThread.start();

        WriteThread writeThread = new WriteThread();
        writeThread.start();

        Thread.sleep(10);
        readThread.interrupt();
        System.out.println("main exit!");
    }

}
